package com.ken.callblock2.view;

import java.nio.channels.GatheringByteChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import ken.app.helper.Helper;

import com.ken.callblock2.CallBlock2;
import com.ken.callblock2.R;
import com.ken.callblock2.R.id;
import com.ken.callblock2.R.layout;
import com.ken.callblock2.adapter.GenView;
import com.ken.callblock2.adapter.GeneralAdapter;
import com.ken.callblock2.listener.PhoneCallListener;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

public class BlockListFragment extends Fragment implements CustomizedView, OnClickListener, OnItemLongClickListener{
	
	private List<BlockItem>	dataList = new ArrayList<BlockItem>();
	private ListView 		mListView ;
	private Button 			mButton;
	private EditText 		mEditText;
	private GeneralAdapter 	adapter;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.activity_main, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		//
		init();
		regListener(true);
	}
	
	private void init(){
		//
		mListView 	= (ListView) 	this.getView().findViewById(R.id.lv_number);
		mButton 	= (Button) 		this.getView().findViewById(R.id.bt_number);
		mEditText 	= (EditText) 	this.getView().findViewById(R.id.et_number);
		//
		adapter = new GeneralAdapter(getActivity(), new BlockItemView());
		adapter.setData(dataList);
		initData(null);
		mListView.setAdapter(adapter);
		//
		getApp().blockListNotifyHandler = notifyHandler;
	}
	
	Handler notifyHandler = new Handler(){
		@Override
		public void dispatchMessage(Message msg) {
			if (adapter != null) {
				initData(null);
				adapter.notifyDataSetChanged();
			}
		}
	};
	
	private void initData(BlockItem data){
		Map<String, String> numbers = getApp().getBlockNubMap();
		if (data != null) {
			dataList.remove(data);
		}else{
			dataList.clear();
			if (numbers.size() > 0) {
				Iterator iterator = numbers.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry entry = (Entry) iterator.next();
					String number = (String) entry.getKey();
					String status = (String) entry.getValue();
					dataList.add(new BlockItem(number, status));
				}
			}
			
		}
	}
	
	public CallBlock2 getApp(){
		return (CallBlock2)getActivity().getApplicationContext();
	}
	
	class BlockItem {
		public String number;
		public String status;
		public String name;
		public int iconRes;
		public BlockItem(String number, String status) {
			this.number = number;
			this.status = status;
			setIcon(status);
		}
		private void setIcon(String status){
			int s = 0;
			if (status.length() > 0) {
				try {
					s = Integer.valueOf(status);
				} catch (Exception e) {
					// TODO: handle exception
				}
				// 設圖示
				if (s == PhoneCallListener.RINGER_MODE_EndCall) {
					iconRes = R.drawable.blockphone;
				}
				if (s == PhoneCallListener.RINGER_MODE_Silent) {
					iconRes = R.drawable.mute;
				}
				if (s == PhoneCallListener.RINGER_MODE_Vibrate) {
					iconRes = R.drawable.vibrate;
				}
			}else{
				iconRes = 0;
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2,long arg3) {
		Helper.ShowMessage(
				getActivity(), 	"",	"是否刪除", 2, new String[]{"刪除", "取消"},
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						getApp().removeBlackItem(dataList.get(arg2).number);
						initData(dataList.get(arg2));
						notifyHandler.sendEmptyMessage(0);
					}
				}, null, null);
		
		return false;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		
		if (id == R.id.bt_number) {
			//關閉輸入法
			InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			in.hideSoftInputFromWindow(mEditText.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			//
			String edit = mEditText.getText().toString();
			if (!edit.equals("") ) {
				getApp().addBlackMap(edit, String.valueOf(PhoneCallListener.RINGER_MODE_EndCall));
				getApp().getBlockNubMap();
				initData(null);
				notifyHandler.sendEmptyMessage(0);
			}else{
				// 無號碼
				getApp().addBlackMap(getResources().getString(R.string.no_number), String.valueOf(PhoneCallListener.RINGER_MODE_EndCall));
				getApp().getBlockNubMap();
				initData(null);
				notifyHandler.sendEmptyMessage(0);
			}
			mEditText.setText("");
		}
	}

	@Override
	public void onDestroyView() {
		regListener(false);
		super.onDestroyView();
	}
	
	@Override
	public void regListener(boolean on) {
		if ( mButton != null)	mButton.setOnClickListener(on ? this : null);
		if ( mListView != null)	mListView.setOnItemLongClickListener(on ? this : null);
	}
	
	
	//-------------------------------------------------------------------------------------------------//
	
	class BlockItemView extends GenView {
		//
		private LayoutInflater inflater;
		//
		public class ViewHolder {
			ImageView 	icon;
			TextView 	title;
		}
		
		@Override
		protected View genBody(Context context, View convertView, Object element, final int position) {
			if(inflater == null) inflater = LayoutInflater.from(context);
			
			ViewHolder holder;
			if(convertView != null && convertView.getTag() instanceof ViewHolder) {
				holder = (ViewHolder) convertView.getTag();
			}else{
				convertView = inflater.inflate(R.layout.row, null);
				holder 			= new ViewHolder();
				holder.title	= (TextView)	convertView.findViewById(R.id.row_title);
				holder.icon		= (ImageView)	convertView.findViewById(R.id.row_icon);
				//
				convertView.setTag(holder);
			}
			//
			BlockItem data = (BlockItem) element;
			//
			holder.title.setText(data.number);
			holder.icon.setImageResource(data.iconRes);
			//
			return convertView;
		}
	}

	//-------------------------------------------------------------------------------------------

}
